<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.res_person"
          placeholder="负责人查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-ab
          placeholder="项目经理"
          v-model="abPerson"
          :table-name="tableName"
          :searchParams="{ 'register_status.eq': 3 }"
          clearable
          @change="handleAbChange"
        ></select-ab>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          placeholder="权证状态"
          @change="getData()"
          v-model="params['transfer_status.eq']"
          :options="enumTransferStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :stripe="false" :columns="tableColumns" :data="tableData">
      <template v-slot:status="scope">
        <div>{{ scope.row.statusLabel }}</div>
        <div>[{{ scope.row.guaType }}]</div>
      </template>
      <template v-slot:name="scope">
        <div class="status-label badge-info text-left w-100">
          <div>A角:{{ scope.row.res_a_name }}</div>
          <div>B角:{{ scope.row.res_b_name }}</div>
        </div>
      </template>
      <template v-slot:approve="scope">
        <div class="badge" :class="`badge-${scope.row.approveStatusCss}`">
          {{ scope.row.approveStatusLabel }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <transfer-table-dialog
      :visible.sync="visible"
      @success="getData()"
      :is-approve="isApprove"
      :register-id="registerId"
      :view-mode="viewMode"
    >
      <table
        class="table text-center table-bordered table-vertical-middle"
        v-if="+viewData.transfer_status > 1"
      >
        <colgroup>
          <col width="30%" />
          <col width="15%" />
          <col width="15%" />
          <col width="20%" />
          <col width="20%" />
        </colgroup>
        <thead>
          <tr>
            <th>项目名称</th>
            <th>权证状态</th>
            <th>交接人</th>
            <th>操作时间</th>
            <th>备注说明</th>
          </tr>
        </thead>
        <tr>
          <td>{{ viewData.customer_name }}</td>
          <td>【{{ enumTransferStatus[viewData.transfer_status] }}】</td>
          <td>{{ viewData.lend_person }}</td>
          <td>{{ viewData.lend_time }}</td>
          <td>{{ viewData.lend_des }}</td>
        </tr>
      </table>
    </transfer-table-dialog>

    <warrants-handle-dialog
      :visible.sync="lendVisible"
      :status="transferStatus"
      @success="getData()"
      :form-data="formData"
    ></warrants-handle-dialog>

    <warrants-history :visible.sync="historyVisible" :id="historyId"></warrants-history>
  </div>
</template>

<script>
import { enumGuaType } from '@/credit/views/city/risk/pledge/enum'
import { enumTransferStatus, enumTransferStatusStyle } from '@/credit/views/city/archives/mixins'
import SelectAb from '@/credit/views/city/archives/SelectAb'
import TransferTableDialog from '@/credit/views/city/risk/pledge/TransferTableDialog'
import WarrantsHandleDialog from '@/credit/views/city/archives/WarrantsHandleDialog'
import WarrantsHistory from '@/credit/views/city/archives/WarrantsHistory'
import { mapGetters } from 'vuex'
export default {
  components: {
    SelectAb,
    TransferTableDialog,
    WarrantsHandleDialog,
    WarrantsHistory,
  },
  props: {},
  data() {
    return {
      enumTransferStatus,
      loading: false,
      params: {
        index: 1,
        size: 15,
        'register_status.eq': 3,
        'transfer_status.gt': 0,
      },
      order: {},
      abPerson: '',
      tableName: 'guaranty_register_view',
      tableData: [],
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: 140 },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '负责人', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '贷款金额(万元)', prop: 'itemFunds', align: 'center' } },
        { attrs: { label: '项目状态', prop: 'projectStatus', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '项目经理', prop: 'resName', align: 'center', minWidth: 90 },
          slot: 'name',
        },
        {
          attrs: { label: '权证数量', prop: 'register_count', align: 'center' },
          process: v => v || '-',
        },
        {
          attrs: {
            label: '权证接收时间',
            prop: 'transfer_approval_time',
            align: 'center',
            minWidth: 100,
          },
          process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd hh:mm') || '-',
        },
        {
          attrs: { label: '权证状态', prop: 'approveStatusLabel', align: 'center' },
          slot: 'approve',
        },
        {
          attrs: {
            label: '权证更新时间',
            prop: 'latest_lend_time',
            align: 'center',
            minWidth: 100,
          },
          process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd hh:mm') || '-',
        },
        {
          attrs: { label: '操作', align: 'center', minWidth: 170 },
          operations: [
            {
              name: '移交审核',
              attrs: { class: 'm-0 p-1' },
              event: this.handleMoveTo,
              ifRender: row => +row.transfer_status === 1 && this.isArchiveManager,
            },
            {
              name: '借出',
              attrs: { class: 'm-0 p-1' },
              event: row => this.handleLend(row, 3),
              ifRender: row => +row.transfer_status === 2 && this.isArchiveManager,
            },
            {
              name: '归还',
              attrs: { class: 'm-0 p-1' },
              event: row => this.handleLend(row, 2),
              ifRender: row => +row.transfer_status === 3 && this.isArchiveManager,
            },
            {
              name: '退还',
              attrs: { class: 'm-0 p-1' },
              event: row => this.handleLend(row, 4),
              ifRender: row => +row.transfer_status === 2 && this.isArchiveManager,
            },
            {
              name: '查看',
              attrs: { class: 'm-0 p-1' },
              event: this.handleView,
              ifRender: row => +row.transfer_status > 1,
            },
            {
              name: '记录',
              attrs: { class: 'm-0 p-1' },
              event: this.handleHistory,
              ifRender: row => row.transfer_status > 1,
            },
          ],
        },
      ],
      totalCount: 0,
      visible: false,
      viewMode: false,
      isApprove: false,
      registerId: '',
      lendVisible: false,
      formData: {},
      // 3 借出
      transferStatus: 3,
      historyVisible: false,
      historyId: '',
      viewData: {},
    }
  },
  computed: {
    ...mapGetters(['user']),
    isArchiveManager() {
      return this.user.scopeArr.includes('archiveM')
    },
  },
  watch: {},
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    handleHistory(row = {}) {
      this.historyId = row.guaranty_register_id
      this.historyVisible = true
    },
    handleLend(row = {}, status) {
      this.formData = { ...row }
      this.transferStatus = status
      this.lendVisible = true
    },
    getHistory(id) {
      const params = {
        index: 1,
        size: 1,
        'register_id.eq': id,
      }
      return this.$api.getData(this.$serviceName, 'lend_register', params, { create_time: 'desc' })
    },
    handleMoveTo(row = {}) {
      this.registerId = row.guaranty_register_id
      this.viewData = { ...row }
      this.isApprove = true
      this.viewMode = true
      this.visible = true
    },
    handleView(row = {}) {
      this.registerId = row.guaranty_register_id
      this.viewData = { ...row }
      this.getHistory(this.registerId).then(res => {
        const data = res?.data?.data?.[0] ?? {}
        this.viewData.lend_person = data.lend_person
        this.viewData.lend_des = data.lend_des
        this.viewData.lend_time = this.$utils.dateFormat(data.lend_time, 'yyyy年MM月dd日')
        this.viewData = { ...this.viewData }
      })
      this.isApprove = false
      this.viewMode = true
      this.visible = true
    },
    handleAbChange() {
      const { abPerson = '' } = this
      this.params['orWhere.res_a.eq'] = abPerson
      this.params['orWhere.res_b.eq'] = abPerson
      this.getData()
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = (data?.data ?? []).map(this.dataAdapter)
          this.totalCount = data?.totalCount ?? 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.resName = `A角: ${item.res_a_name} B角: ${item.res_b_name}`
      item.guaType = enumGuaType[item.gua_type]
      if (+item.load_beh_status === 6) {
        item.statusLabel = '已完结'
      } else if (+item.loan_approval_status === 2) {
        item.statusLabel = '已放款'
      } else {
        item.statusLabel = '核保中'
      }
      item.projectStatus = `${item.statusLabel} - ${item.guaType}` // 导出时使用
      item.approveStatusLabel = enumTransferStatus[item.transfer_status] || '-'
      item.approveStatusCss = enumTransferStatusStyle[item.transfer_status] || ''
      item.itemFunds = item.reply_funds || item.res_funds || '-'
      return item
    },
  },
}
</script>

<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
